package com.lry.basic.jvm.classLoader;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/12/4
 */
public class ClassLoaderTest {
    public static void main(String[] args) throws ClassNotFoundException {
        ClassLoader loader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
                    InputStream is = getClass().getResourceAsStream(fileName);
                    if(is==null){
                        return super.loadClass(name);
                    }
                    byte[] b = new byte[is.available()];
                    is.read(b);

                    return defineClass(name,b,0,b.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };

        Class clazz = loader.loadClass("com.lry.basic.jvm.classLoader.ClassLoaderTest");
        System.out.println(clazz);

        System.out.println(clazz.getClassLoader());

        //不是同一个类加载器加载类，即使class文件一样，所生成的类也是不一样的
        System.out.println(clazz == ClassLoaderTest.class);

    }
}
